import { createHashRouter, Navigate } from "react-router";
import type { RouteObject } from "react-router";
import { createElement } from "react";

// 动态加载路由文件
// 匹配所有 .router.tsx 或 .router.jsx 文件
const pages = import.meta.glob("/src/pages/**/*.{router.tsx,router.jsx}", {
  eager: true,
});

// 动态加载 meta 文件
// 匹配所有 .meta.ts 或 .meta.js 文件
const metas = import.meta.glob("/src/pages/**/*.meta.{ts,js}", { eager: true });

// 动态加载布局组件
const layoutModules = import.meta.glob("/src/layout/*.tsx", { eager: true });
const layouts = Object.fromEntries(
  Object.entries(layoutModules).map(([path, module]) => {
    // 如果是 index.tsx，使用 DefaultLayout 作为键名
    const name = path.endsWith("/index.tsx")
      ? "DefaultLayout"
      : path.match(/\/layout\/(.*)\.tsx$/)?.[1];
    return [name || "DefaultLayout", (module as ModuleWithDefault).default];
  })
);

// 定义路由元数据类型
interface Meta {
  index?: boolean;
  title?: string;
  layout?: string;
  [key: string]: unknown;
}

// 定义模块类型
interface ModuleWithDefault {
  default: React.ComponentType;
}

// 定义路由映射类型
interface RouteMap {
  [key: string]: {
    path: string;
    element?: React.ReactNode;
    children: RouteMap;
    meta?: Meta;
    index?: boolean;
  };
}

/**
 * 生成路由配置
 * @param basePath 基础路径，默认为 "/src/pages"
 * @returns 路由配置数组
 */
const generateRoutes = (basePath = "/src/pages"): RouteObject[] => {
  console.log(pages);
  // 用于存储路由映射的对象
  const routeMap: RouteMap = {};

  // 遍历所有页面文件
  Object.entries(pages).forEach(([path, module]) => {
    // 处理文件路径，转换为路由路径
    // 例如：/src/pages/Home/Info/index.router.tsx -> /home/info
    const routePath = path
      .replace(basePath, "")
      .replace(/\/index\.router\.(tsx|jsx)$/, "")
      .toLocaleLowerCase();

    // 处理根路径
    const fullPath = routePath === "" ? "/" : routePath;

    // 获取路由的元数据（meta.ts 或 meta.js）
    const metaTsName = path.replace(/\.router\.(tsx|jsx)$/, ".meta.ts");
    const metaJsName = path.replace(/\.router\.(tsx|jsx)$/, ".meta.js");
    const metaModule = (metas[metaTsName] ||
      metas[metaJsName]) as ModuleWithDefault;
    const meta = (metaModule?.default || {}) as unknown as Meta;

    // 创建路由节点
    routeMap[fullPath] = {
      path: fullPath,
      element: createElement((module as ModuleWithDefault).default),
      children: {},
      meta,
      index: meta.index ? true : undefined,
    };

    // 处理父级路由
    const parentPath = fullPath.split("/").slice(0, -1).join("/") || "/";
    if (parentPath !== fullPath) {
      if (!routeMap[parentPath]) {
        routeMap[parentPath] = {
          path: parentPath,
          children: {},
        };
      }
      routeMap[parentPath].children[fullPath] = routeMap[fullPath];
    }
  });

  console.log(routeMap);

  /**
   * 将路由映射转换为 React Router 的路由配置数组
   * @param routeObj 路由映射对象
   * @returns 路由配置数组
   */
  const convertToRoutesArray = (routeObj: RouteMap): RouteObject[] => {
    return Object.entries(routeObj).map(([, route]) => {
      // 递归处理子路由
      const children =
        Object.keys(route.children).length > 0
          ? convertToRoutesArray(route.children)
          : undefined;

      // 处理 index 路由和重定向
      if (children) {
        // 查找 index 路由
        const indexRoute = children.find((child) => child.index);
        // 如果存在 index 路由且当前路由没有组件，添加重定向
        if (indexRoute && !route.element) {
          const routeObject: RouteObject = {
            path: route.path,
            children: [
              {
                index: true,
                path: route.path,
                // 重定向到 index 路由
                element: <Navigate to={indexRoute.path || "/"} replace />,
              },
              ...children,
            ],
          };
          return routeObject;
        }

        // 获取布局组件
        const layoutName = route.meta?.layout ?? "DefaultLayout";
        const LayoutComponent = layouts[layoutName];
        if (LayoutComponent) {
          return {
            path: route.path,
            element: createElement(LayoutComponent),
            children,
          };
        }
      }

      // 创建路由对象
      const routeObject: RouteObject = {
        path: route.path,
        element: route.element,
        children,
        handle: route.meta,
      };
      return routeObject;
    });
  };

  // 创建根路由，包含所有自动读取的路由作为 children
  const rootRoute: RouteObject = {
    path: "/",
    children: [
      // 根路径重定向到 /home
      {
        index: true,
        path: "/",
        element: <Navigate to="/home" replace />,
      },
      // 添加其他路由
      ...convertToRoutesArray(routeMap),
    ],
  };

  return [rootRoute];
};

const routes = generateRoutes();
console.log(routes);

export const router = createHashRouter(routes);
